package com.example.back.utils;

import com.example.back.jpa.SupervisionLogRepository;
import com.example.common.entity.SupervisionLog;

import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

@Component
public class TradeNumUtils {
    @Resource
    private SupervisionLogRepository supervisionLogRepository;

    public SupervisionLog createTradeNum(String hCode) {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        Date now = new Date();
        String num = sdf.format(now) + "-" + hCode;
        String max = supervisionLogRepository.findLastTradeNum(num);
        if(max == null || max.length() == 0)
            num += "-" + "0001";
        else{
            DecimalFormat df =new DecimalFormat ("0000");
            int n = Integer.parseInt(max.split("-")[2]) + 1;
            if(n > 9999){
                createTradeNum(hCode);
            }
            num += "-" + df.format(n);
        }

        if(supervisionLogRepository.findExists(num) > 0)
            createTradeNum(hCode);
        
        SupervisionLog log = new SupervisionLog();
        log.setSendTradeNum(num);
        log.setCreateTime(now);
        log = supervisionLogRepository.save(log);
        if(log == null)
            createTradeNum(hCode);
        return log;
    }
}
